<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>7.简单动画-小试牛刀（弹性球）</title>
    <style>
        .container {
            width: 300px;
            position: relative;
        }
        .block {
            width: 20px;
            height: 20px;
            margin: 10px;
            border-radius: 50px;
            position: absolute;
        }
        .block:nth-child(1) {background: red;}
    </style>
</head>
<body>
    <div class="container">
        <div class="block"></div>
    </div>

    <script type="module">
        
        import {Animator} from '/common/lib/animator.js';
        const block = document.querySelector('.block');
        
        // p = p ** 2; // 匀加速运动
        // p = p * (2 - p); // 匀减速运动
        let start = 0, end = 200, duration = 800;
        let distance = end - start;
        const animator = new Animator({ duration, easing: p => p ** 2 });
        document.addEventListener('click', async () => {
            
            while(Math.abs(distance) >= 0.1){
                // 根据方向更新动画函数
                if(distance > 0)
                    // 向下运动，匀加速
                    animator.updateTiming({easing: p => p ** 2});
                else
                    // 向上运动，匀减速
                    animator.updateTiming({easing: p => p * (2 - p)});

                // 更新动画的周期时间（保持加速度恒定） 
                animator.updateTiming({duration: duration *= 0.7});

                await animator.animate({el: block, start, end}, ({target: {el, start, end}, timing: {p}}) => {
                    const top = start * (1 - p) + end * p;
                    el.style.top = `${top}px`;
                });

                // 通过distance记录运动方向
                distance = - distance / 2;
                // 更新开始与结束的位置变化
                if(distance < 0){
                    [start, end] = [end, end + distance];
                }else{
                    [start, end] = [end, start];
                }
            }
        });
    </script>
</body>
</html>